import { API_HOST, API_PLATFORM, API_VERSION } from './config';
import { alert, toast } from './modal.js';
import { wxLogin } from './wxLogin.js'

// 显示Loading弹窗的请求时间阀值
const SHOW_LOADING_TIME = 1000 * 3;

/**
 * 通用 HTTPS 请求封装
 * 返回 Promise
 * @params method 方法
 * @params api 链接
 * @params data 参数
 * @params header 头部
 * @params { showLoadingMask, loadingTitle }
 * @params showLoading 是否将展示 Loading，默认为展示
 * @params showLoadingMask 是否将 loading 设置为模态，在 showLoading=true 时有效
 * @params loadingTitle Loading 提示文案
 */
const service = function httpRequest({
  method,
  url,
  data = {},
  header = {},
  showLoading = true,
  showLoadingMask = false,
  loadingTitle = '加载中',
  is_alert = false
} = {}
) {
  return new Promise((resolve, reject) => {
    let realUrl = API_HOST + url;
    if (url.includes('https://')) {
      realUrl = url
    }
    let loadingTimr = null;
    if (showLoading) {
      loadingTimr = setTimeout(() => {
        wx.showLoading({
          title: loadingTitle,
          mask: showLoadingMask,
        });
      }, SHOW_LOADING_TIME);
    }

    const commonHeader = {
      'x-platform': 'wx-mini',
      // 'x-version': '0.5.0',
      'x-timestamp': parseInt(Date.now() / 1000)
    };

    for (let headerKey in header) {
      commonHeader[headerKey] = header[headerKey];
    }

    // 将参数对象中的 undefined,null,NaN 剔除
    for (let prop in data) {
      if (data[prop] == null) {
        delete data[prop];
      }
    }

    let retryTimes = 1;

    startRequset(realUrl, data, method, commonHeader, showLoading, resolve, retryTimes, reject, loadingTimr);
  });
}

function startRequset(realUrl, data, method, commonHeader, showLoading, resolve, retryTimes, reject, loadingTimr) {
  if (retryTimes-- < 0) {
    toast('请求异常，请稍后再试');
    return;
  }
  // 添加授权
  const token = wx.getStorageSync('token') || ''
  // console.log('token' , token)
  commonHeader['Authorization'] = token;
  commonHeader['code'] = wx.getStorageSync('code') || '';
  // console.log(realUrl)
  let start = new Date().getTime();
  wx.request({
    url: realUrl,
    data,
    method,
    header: commonHeader,
    success(res) {
      // 服务端返回任何 http 状态码都会进入 success 回调
      const { statusCode, data: respData } = res;
      if (+statusCode == 200) {
        if (respData.error_code > 0) {
          toast(respData.message || '请求失败，请重试');
          if (respData.error_code == 5001) {
            reject(respData);
          }
        } else {
          resolve(respData.data);
        }
      } else if (+statusCode === 401) {
        wxLogin().then(() => {
          startRequset(realUrl, data, method, commonHeader, showLoading, resolve, retryTimes, loadingTimr);
        }).catch(() => {
          wx.showToast({
            title: '请求异常，请稍后再试',
            icon: 'none',
            duration: 2000,
          });
        });
      } else {
        setTimeout(() => {
          toast(respData.error_message || '访问的资源不存在');
        }, 100);
        reject(statusCode);
      }
    },
    fail() {
      // 仅当断网、DNS 异常等网络错误时回调
      toast('网络似乎有问题');
    },
    complete() {
      if (loadingTimr) {
        clearTimeout(loadingTimr);
        loadingTimr = null;
      }
      // if (showLoading) {
      //   wx.hideLoading();
      // }
    }
  });
}
// 业务监控---基础监控--接口监控
function joggleMonitor(monitorId, errorCode, errorMsg, realUrl, time) {

  console.log()
  wx.reportEvent && wx.reportEvent('wxdata_perf_monitor', {
    // 接口ID，可以使用URL相似的ID，也可以另外命名
    "wxdata_perf_monitor_id": monitorId,
    //接口等级，0为普通，非0为重要，数值越大越重要，根据实际业务情况进行设置
    "wxdata_perf_monitor_level": 1,
    // 错误码，0为调用成功，非0为调用失败
    "wxdata_perf_error_code": errorCode,
    // 错误信息，选填，可以上报错误相关信息，方便后续排查问题
    "wxdata_perf_error_msg": errorMsg,
    // 接口耗时，选填
    "wxdata_perf_cost_time": time,
    // 以下为补充字段，可额外上报其他监控信息，用于事件分析，非必填
    "wxdata_perf_extra_info1": realUrl,
    "wxdata_perf_extra_info2": "",
    "wxdata_perf_extra_info3": "",
  })
}
// function addParams(data) {
//   data.fr = 2;
//   data.version = API_VERSION;
//   data.platform = API_PLATFORM;
// }

// function httpGet(url, data = {}, header, options) {
//   data = addParams(data);

//   return httpRequest('GET', url, data, header, options);
// }

// function httpPost(url, data = {}, header, options) {
//   const version = API_VERSION;
//   const platform = API_PLATFORM;

//   return httpRequest(
//     'POST',
//     `${ url }?fr = 2 & version=${ version }& platform=${ platform } `,
//     data,
//     header,
//     options
//   );
// }
export default service

// module.exports = {
//   httpGet,
//   httpPost,
// };
